<template>
  <div class="app-container">
    <el-card shadow="always" :body-style="{ padding: '20px' }">
      <div slot="header">
        <span>批量导入员工</span>
      </div>
      <!-- card body -->
      <UploadExcel :before-upload="beforeUpload" :on-success="onSuccess" />
    </el-card>
  </div>
</template>

<script>
import { formatExcelDate } from '@/utils/index'
import { importEmployees } from '@/api/employees'
export default {
  methods: {
    // file选择的excel文件
    // 上传之前的校验
    // 校验的大小,校验文件格式
    // 校验通过 return true || 失败 return flase
    beforeUpload (file) {
      console.log(file)
      // 只有返回true才会触发onSuccess函数]2
      return true
    },
    // file的读取
    async onSuccess ({ header, results }) {
      // console.log('表头', results)
      console.log(this.transformResults(results))
      await importEmployees(this.transformResults(results))
      this.$router.back()
    },
    transformResults (results) {
      const userMap = {
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      const newResults = []
      results.forEach(item => {
        const newUser = {}
        for (const key in item) {
          const enkey = userMap[key]
          // eslint-disable-next-line no-undef
          if (enkey === 'timeOfEntry' || enkey === 'correctionTime') {
            newUser[enkey] = formatExcelDate(item[key], '-')
          } else {
            newUser[enkey] = item[key]
          }
        }
        newResults.push(newUser)
      })
      return newResults
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
